/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.bus.api;

import com.github.panchitoboy.shiro.jwt.repository.Principal;
import com.github.panchitoboy.shiro.jwt.repository.TokenResponse;
import com.github.panchitoboy.shiro.jwt.repository.UserRepository;
import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.persistence.ResultCode;
import com.thinkgem.jeesite.common.security.shiro.session.SessionDAO;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.bus.entity.Ent;
import com.thinkgem.jeesite.modules.bus.service.AuditService;
import com.thinkgem.jeesite.modules.bus.service.EntService;
import com.thinkgem.jeesite.modules.sys.entity.Attachment;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.AttachmentService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * restful demo
 * 所有的api返回值均为ResponseResult，在ResponseResult内赋予相关的对象
 * @author waile23
 * @version 2017-11-12
 */
@RestController
@RequestMapping(value = "${wechatPath}/rest/ent")
public class RestEntController extends BaseController{

	@Autowired
	private EntService entService;
	@Autowired
	private AuditService auditService;

	@Autowired
	private SessionDAO sessionDAO;
	
	@Autowired
	private UserRepository userRepository;

    @Autowired
    private AttachmentService attachmentService;
	/**
	 * 返回用户信息
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "user", method = RequestMethod.GET)
	public ResponseResult user(){
        return ResponseResult.success(UserUtils.getPrincipal());
	}
	
	/**
	 * 成功，只返回code和message
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "sucess", method = RequestMethod.GET)
	public ResponseResult sucess(){
        return ResponseResult.success();
	}
	
	/**
	 * 成功，返回code和message，并返回一个object对象
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "sucess/data/object", method = RequestMethod.GET)
	public ResponseResult object(){
		Principal principal = UserUtils.getPrincipal();
        TokenResponse token = userRepository.createToken(principal);
        return ResponseResult.success(token);
	}
	
	/**
	 * 成功，返回code和message，并返回一个List对象
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "sucess/data/list", method = RequestMethod.GET)
	public ResponseResult list(){
		Principal principal = UserUtils.getPrincipal();
        TokenResponse token = userRepository.createToken(principal);
        
        List<TokenResponse> tokenList = new ArrayList<TokenResponse>();
        tokenList.add(token);
        tokenList.add(token);
        tokenList.add(token);
        return ResponseResult.success(tokenList);
	}
	
	/**
	 * 成功，返回code和message，并返回一个map对象
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "sucess/data/map", method = RequestMethod.GET)
	public ResponseResult map(){
		Principal principal = UserUtils.getPrincipal();
        TokenResponse token = userRepository.createToken(principal);
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("tokenData", token);
        return ResponseResult.success(results);
	}
	
	/**
	 * 失败
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "failure", method = RequestMethod.GET)
	public ResponseResult failure(){
		return ResponseResult.failure(ResultCode.FAILED);
	}
	
	/**
	 * 失败，自定义错误信息
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * 服务器在shiro中验证Token是否符合要求
	 * @return
	 */
	@RequestMapping(value = "error", method = RequestMethod.GET)
	public ResponseResult errorMsg(){
		return ResponseResult.failure("出现错误！");
	}
	
	/**
	 * POST Map
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "post/map", method = RequestMethod.POST)
	public ResponseResult postMap(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response){
		return ResponseResult.success(map);
	}
	
	/**
	 * POST Obj
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "post/obj", method = RequestMethod.POST)
	public ResponseResult postObj(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){
		return ResponseResult.success(user);
	}
	
	/**
	 * POST Obj
	 * 需要在请求Header中将Login返回的Token写入Authorization字段中。
	 * @param principal
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "post/principal", method = RequestMethod.POST)
	public ResponseResult postObj(@RequestBody Principal principal, HttpServletRequest request, HttpServletResponse response){
		return ResponseResult.success(principal);
	}

	/***
	 * @Author zhangxingliang
	 * @Description 获取养殖场信息
	 * @Date 9:02 2019/6/4
	 * @Param [id]
	 * @return com.thinkgem.jeesite.common.persistence.ResponseResult
	 **/
	@RequestMapping(value = "get/{id}", method = RequestMethod.GET)
	public ResponseResult get(@PathVariable(value = "id") String id) throws Exception {
		Ent ent = this.entService.get(id);
		ent.setGradeTypeCodeLabel(DictUtils.getDictLabel(ent.getGradeType(),"entGrade",""));
        List<Attachment> attachmentList = attachmentService.findListByTable(ent.getId(), "bus_ent");
        ent.setAttachmentList(attachmentList);
        List<Map<String, Object>> list = entService.findEntAnimalList(id);
        ent.setDicList(list);
		return ResponseResult.success(ent);
	}

	/***
	 * @Author zhangxingliang
	 * @Description 养殖场备案
	 * @Date 11:24 2019/6/3
	 * @Param [ent, request, response]
	 * @return com.thinkgem.jeesite.common.persistence.ResponseResult
	 **/
	@RequestMapping(value = "edit" )
	public ResponseResult edit(@RequestBody Ent ent, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            this.entService.edit(ent);
        } catch(Exception e) {
            return ResponseResult.failure("编辑失败，错误如下：" + e.getMessage());
        }
		return ResponseResult.success();
	}

	/***
	 * @Author zhangxingliang
	 * @Description 获取养殖场养殖品种列表 暂时无用
	 * @Date 9:03 2019/6/4
	 * @Param [id, request, response]
	 * @return com.thinkgem.jeesite.common.persistence.ResponseResult
	 **/
	@ResponseBody
	@RequestMapping(value = "findEntAnimalList/{id}", method = RequestMethod.GET)
	public ResponseResult searchListByType(@PathVariable(value = "id") String id, HttpServletRequest request, HttpServletResponse response){
		List<Map<String, Object>> list = this.entService.findEntAnimalList(id);
		return ResponseResult.success(list);
	}


	@RequestMapping(value = "/upload/image", method = RequestMethod.POST)
	public ResponseResult uploadImage(@RequestParam(required = false) MultipartFile file, Attachment attachment,
		HttpServletRequest request, HttpServletResponse response) {
		try {
			this.entService.uploadImg(attachment, request);
			return ResponseResult.success();
		} catch(Exception e) {
			return ResponseResult.failure("图片上传失败，错误如下：" + e.getMessage() );
		}
	}

	/**
	 *
	 * @Title: uploadFile
	 * @author: wzl
	 * @date: 2018年9月18日 下午1:47:35
	 * @Description: 上传文件
	 * @param: file
	 * @param: request
	 * @param: response
	 * @return: ResponseResult
	 * @throws:
	 */
	@RequestMapping(value = "/upload/file", method = RequestMethod.POST)
	public ResponseResult uploadFile(@RequestParam MultipartFile file,
		HttpServletRequest request, HttpServletResponse response) {
		try {
			return ResponseResult.success();
		} catch(Exception e) {
			return ResponseResult.failure("图片上传失败，错误如下：" + e.getMessage() );
		}
	}


	@RequestMapping(value = "/upload/img", method = RequestMethod.POST)
	public ResponseResult uploadImg(@RequestBody String base,
		HttpServletRequest request, HttpServletResponse response) {
		try {
			return ResponseResult.success();
		} catch(Exception e) {
			return ResponseResult.failure("图片上传失败，错误如下：" + e.getMessage() );
		}
	}
	/**
	 * @Author zhangxingliang
	 * @Description 删除图片记录 同时删除七牛服务器图片
	 * @Date 14:12 2019/6/11
	 * @Param [attachment, request, response]
	 * @return com.thinkgem.jeesite.common.persistence.ResponseResult
	 **/
	@RequestMapping(value = "/delete/image", method = RequestMethod.POST)
	public ResponseResult deleteImage(@RequestBody Attachment attachment, HttpServletRequest request,HttpServletResponse response) {
		try {
			attachmentService.deleteQiniu(attachment);
			return ResponseResult.success();
		} catch(Exception e) {
			return ResponseResult.failure("图片删除失败，错误如下：" + e.getMessage() );
		}
	}

	/**
	 * @Author zhangxingliang
	 * @Description 获审核状态
	 * @Date 18:49 2019/6/11
	 * @Param [id]
	 * @return java.lang.String
	 **/
	@RequestMapping(value = "/auditStatus/{tableId}/{tableName}", method = RequestMethod.GET)
	public ResponseResult getAuditStatus(@PathVariable(value = "tableId") String tableId,@PathVariable(value = "tableName") String tableName) throws Exception {
		Map<String, Object> map = this.auditService.getAuditStatus(tableId,tableName);
			if( null == map){
				map = new HashMap<>();
				map.put("auditStatus","-1");
			}
		return ResponseResult.success(map);
	}

	/**
	 * @author Zhang Xingliang
	 * @description 养殖场法人身份证唯一性校验
	 * @date 14:21 2019/6/26
	 * @params [idCard]
	 * @return java.lang.String
	 **/
	@RequestMapping(value = "/checkIdCard/{idCard}", method = RequestMethod.GET)
	public ResponseResult checkIdCardExist(@PathVariable(value = "idCard") String idCard){
		User user = UserUtils.getUser();
		if(null == user.getId()){
			return ResponseResult.failure("未找到用户" );
		}
		String msg = this.entService.checkIdCardExist(idCard,user.getId());
		return ResponseResult.success(msg);
	}
}